/**
 * 
 */
package com.example.helpconnect;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.NumberFormat;
import java.util.Locale;

import com.example.controller.SMSUtility;
import com.example.controller.Service;
import com.example.controller.ServiceStatus;
import com.example.controller.User;
import com.example.model.ServiceCRUD;
import com.example.model.ServiceStatusCRUD;
import com.example.model.UserCRUD;


import android.app.ActionBar;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalActivity;
import com.paypal.android.MEP.PayPalReceiverDetails;
import com.paypal.android.MEP.PayPalPayment;
import com.paypal.android.MEP.PayPalInvoiceData;
import com.paypal.android.MEP.PayPalInvoiceItem;


/**
 * @author Joseph
 *
 */


public class RequestedServiceViewActivity extends Activity {

	User user, requested_user, requesting_user;
	ServiceStatus serv_stat, targetSS;
	Service service, target_service;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    
	    setContentView(R.layout.requested_service_view);
	    
	    PayPal ppObj = PayPal.initWithAppID(this, "APP-80W284485P519543T", PayPal.ENV_SANDBOX);
	    
	    
	    
	    
	    
		
	    Intent intent = getIntent();
	    
	    int ssID = intent.getIntExtra("ssID", -1);
	    
	    serv_stat = new ServiceStatus(new ServiceStatusCRUD());
	    ServiceStatus targetSS = serv_stat.read(ssID);
	    int requested_user_id = targetSS.getServiceOwnerID();
	    int requesting_user_id = targetSS.getRequesterUserID();
	    
	    user = new User(new UserCRUD());
	    requested_user = user.read(requested_user_id);
	    requesting_user = user.read(requesting_user_id);
	    
	    ImageView user_picture;
	    user_picture = (ImageView)findViewById(R.id.quickContactBadge1);
	    URL img_value = null;
	    try {
			img_value = new URL("http://graph.facebook.com/"+requested_user_id+"/picture?type=large");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    Bitmap mIcon1 = null;
		try {
			mIcon1 = BitmapFactory.decodeStream(img_value.openConnection().getInputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		user_picture.setImageBitmap(mIcon1);
		
		EditText requested_from = (EditText)findViewById(R.id.requested_from_name);
		EditText requested_at = (EditText)findViewById(R.id.time_stamp);
		CheckBox service_paid_checkbox = (CheckBox)findViewById(R.id.service_paid_checkbox);
		CheckBox service_connected_checkbox = (CheckBox)findViewById(R.id.service_connected_checkbox);
		EditText service_description = (EditText)findViewById(R.id.requested_service_description_field);
		EditText price_field = (EditText)findViewById(R.id.price_field);
		
		service = new Service(new ServiceCRUD());
		target_service = service.read(targetSS.getServiceID());
		
		final double costOfService = target_service.getCost();
    	NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US);
    	String cost = fmt.format(costOfService);
    	
    	price_field.setText(cost);
    	requested_from.setText(requested_user.getFirstName() +" "+requested_user.getLastName());
    	requested_at.setText(targetSS.getTimeStamp());
    	service_paid_checkbox.setChecked(targetSS.isPaid());
    	service_connected_checkbox.setChecked(targetSS.isConnected());
    	service_description.setText(target_service.getDescription());
    	
	
    	CheckoutButton launchPayPalButton = ppObj.getCheckoutButton(this, PayPal.BUTTON_278x43, CheckoutButton.TEXT_PAY);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		params.bottomMargin = 10;
		launchPayPalButton.setLayoutParams(params);
		launchPayPalButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				PayPalPayment newPayment = new PayPalPayment();
				newPayment.setSubtotal(new BigDecimal(Double.toString(costOfService)));
				newPayment.setCurrencyType("USD");
				//The recipient is hard-coded for testing purposes
				newPayment.setRecipient("pjones_1354507159_biz@gmail.com");
				newPayment.setMerchantName(requested_user.getFirstName() + " " + requested_user.getLastName());
				Intent paypalIntent = PayPal.getInstance().checkout(newPayment, RequestedServiceViewActivity.this);
				RequestedServiceViewActivity.this.startActivityForResult(paypalIntent, 1);
				
			}
		});
		((RelativeLayout)findViewById(R.id.profile_pic)).addView(launchPayPalButton);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

	   switch(resultCode) {

	      case Activity.RESULT_OK:
	    	  System.out.println("IN OK");
	    	  updatePayment();
	          break;

	       case Activity.RESULT_CANCELED:
	    	   System.out.println("IN CANCEL");
	           break;

	       case PayPalActivity.RESULT_FAILURE:
	    	   System.out.println("IN FAIL");
	  }

	}
	
	public void updatePayment(){
		this.targetSS.setPaid(true);
  	  	this.targetSS.update();
  	  	CheckBox service_paid_checkbox = (CheckBox)findViewById(R.id.service_paid_checkbox);
  	  	service_paid_checkbox.setChecked(true);
  	  	final double costOfService = this.target_service.getCost();
    	NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US);
    	String cost = fmt.format(costOfService);
  	  	String message = "**HelpConnect Message**\n";
	    message += this.requested_user.getFirstName() + " " + this.requested_user.getLastName() + " has recieved your payment of " + cost + ".";
	    SMSUtility smsTool = new SMSUtility(this.targetSS.getRequesterUserID(), message);
	    smsTool.sendSMS();
	    String message2 = "**HelpConnect Message**\n";
	    message2 += this.requesting_user.getFirstName() + " " + this.requesting_user.getLastName() + " just made a payment of " + cost + "to you. Check your PayPal account for details.";
	    smsTool = new SMSUtility(this.targetSS.getServiceOwnerID(), message2);
	    smsTool.sendSMS();
	}
	
	@Override
	public void onResume(){
		
		super.onResume();
		
		Intent intent = getIntent();
	   
		int ssID = intent.getIntExtra("ssID", -1);
	    
	    serv_stat = new ServiceStatus(new ServiceStatusCRUD());
	    this.targetSS = serv_stat.read(ssID);
	    int requested_user_id = targetSS.getServiceOwnerID();
	    
	    user = new User(new UserCRUD());
	    requested_user = user.read(requested_user_id);
	}

}
